const {ccclass, property} = cc._decorator;

@ccclass
export default class joystick extends cc.Component {

    @property(cc.Node)
    stick: cc.Node = null;

    @property({tooltip: '最大半径'})
    max_R: number = 100;
    @property({tooltip: '最小半径'})
    min_R: number = 20;
    // 方向
    public dir: cc.Vec2 = cc.v2(0, 0)

    onLoad () {
        this.stick.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
        this.stick.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this)
        this.stick.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
    }
    // 监听stick事件触摸
    onTouchMove(e: cc.Touch){
        // 获取到屏幕坐标
        const screen_pos: cc.Vec2 = e.getLocation();
        // 将屏幕坐标转换成节点坐标
        const pos: cc.Vec2 = this.node.convertToNodeSpaceAR(screen_pos)
        const len: number = pos.mag() //向量的长度

        this.dir.x = pos.x / len; // (cos)
        this.dir.y = pos.y / len; // (sin)
        if (len < this.min_R) {
            this.stick.setPosition(pos)
            return
        }
        if (len > this.max_R) {
            pos.x = pos.x * this.max_R / len;
            pos.y = pos.y * this.max_R / len;
        }
        this.stick.setPosition(pos)
    }
    // 监听触摸结束
    onTouchEnd(){
        this.dir = cc.v2(0,0)
        this.stick.setPosition(cc.v2(0, 0))
    }

    start () {

    }

    // update (dt) {}
}
